package liyan.shi.springboot.controller;

import liyan.shi.springboot.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自己定制异常处理类
 */
@ControllerAdvice
public class MyExceptionHandler {

    //处理UserNotExistException异常,响应自定义数据
    //浏览器和客户端响应的都是json
//    @ResponseBody
//    @ExceptionHandler({UserNotExistException.class})
//    public Map<String, Object> handlerException(Exception e){
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", "user.notExist");
//        map.put("message", e.getMessage());
//        return map;
//    }

    @ExceptionHandler({UserNotExistException.class})
    public String handlerException(Exception e, HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        //要传入我们自己的状态码, 否则状态码为200
        //Integer statusCode = (Integer) request
        //        .getAttribute("javax.servlet.error.status_code");
        request.setAttribute("javax.servlet.error.status_code", 500);
        map.put("code", "user.notExist");
        map.put("message", e.getMessage());
        request.setAttribute("ext", map);
        //转发到/error
        return "forward:/error";
    }
}
